package com.superbit.utils.configutil;

import java.io.File;
import java.io.FileInputStream;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.beans.factory.config.PropertyPlaceholderConfigurer;
import org.springframework.util.CollectionUtils;

public class SpringPropertyConfiguer extends PropertyPlaceholderConfigurer {
	private Logger logger = LoggerFactory.getLogger(this.getClass());

	//保存所有最后的配置信息
	private Map<String,Object> finalProperties = new HashMap<String,Object>();
	
	public String getProperty(String key){
		Object value = finalProperties.get(key);
		if(value==null)return null;
		else return value+"";
	}
	
	@Override
	protected void processProperties(ConfigurableListableBeanFactory beanFactoryToProcess, Properties props)throws BeansException {
		//此方法用于使用外部配置文件替换现有配置，  方法是在config目录下 新增一个conf文件， 在内容中加入 serverconfigdir = XXXXXXXX
		//系统会扫描所配置目录中的所有.conf,.ini,.properties文件， 并将其中内容替换到系统中
		Object dbconfigdir = props.get("serverconfigdir");
		if(dbconfigdir!=null){
			try{
				logger.info("加载外部配置文件夹："+dbconfigdir);
				String str = dbconfigdir.toString();
				File f = new File(str);
				if(f.exists()&&f.isDirectory()){
					String[] filenames = f.list();
					for(String finame:filenames){
						String downcase = finame.toLowerCase();
						if(downcase.endsWith(".conf")||downcase.endsWith(".ini")||downcase.endsWith(".properties")){
							try {
								Properties p = new Properties();
								p.load(new FileInputStream(dbconfigdir+"/"+finame));
								logger.error("更新内容："+finame+","+p);
								CollectionUtils.mergePropertiesIntoMap(p, props);
							} catch (Exception e) {
								logger.info("无法加载文件："+dbconfigdir+"/"+finame);
							}
						}
					}
				}
			}catch(Exception e){
				logger.error(e.getMessage(),e);
			}
		}
		CollectionUtils.mergePropertiesIntoMap(props, finalProperties);
		super.processProperties(beanFactoryToProcess, props);
	}
}
